'use strict';

const uidObj = require('uni-id')
const {
	Controller
} = require('uni-cloud-router')

module.exports = class UserController extends Controller {
	async loginV2() {
		const {
			username,
			password,
			cid
		} = this.ctx.data
		
		const nowdate = Date.now();
		
		let res = await uidObj.login({
			username,
			password,
			needPermission: true
		})
		// console.log(res);
		uniCloud.logger.info('user res', res)
		if (res.code === 0) {
			delete res.userInfo.password;
			delete res.userInfo.password_secret_version;
			delete res.userInfo.token;
			if (res.userInfo.role.indexOf('admin') == -1) {
				// 获取角色权限
				const roleRes = await this.db.collection('uni-id-roles').where({
					role_id: this.db.command.in(res.userInfo.role)
				}).get()
				uniCloud.logger.info('获取角色权限', roleRes)
	
				let permissions = [];
				roleRes.data.forEach(x => {
					permissions = [...new Set([...permissions, ...x.permission])]
				});
	
				res.userInfo.permission = permissions
			}
	
			// 请求本地存储数据
			res.historyStorageRes = await this.db.collection('usemall-history-storage').doc(res.userInfo._id)
				.get()
	
			// 请求菜单数据
			let objWhere = {
				enable: true
			}
			if (res.userInfo.role.indexOf('admin') == -1) {
				objWhere._id = this.db.command.in(res.userInfo.permission)
			}
	
			res.menuRes = await this.db.collection('opendb-admin-menus').where(objWhere).orderBy('sort', 'asc')
				.get()
		}
	
		// 添加设备记录
		console.log('context', this.ctx.context)
		const {
			deviceId
		} = this.ctx.context
		// 记录 device、user、unipush_clientid 关系
		const deviceUpdateRes = await this.db.collection('uni-id-device').doc(deviceId).update({
			context: this.ctx.context,
	
			user_id: res.uid,
			token_expired: res.tokenExpired,
			push_clientid: cid,
			unipush_clientid: cid,
	
			login_cnt: this.db.command.inc(1),
			last_active_date: nowdate,
			last_active_ip: this.ctx.data.ip || this.ctx.context.CLIENTIP
		})
	
		if (deviceUpdateRes && deviceUpdateRes.updated <= 0) {
			await this.db.collection('uni-id-device').doc(deviceId).set({
				context: this.ctx.context,
	
				uuid: deviceId,
				device_id: deviceId,
	
				user_id: res.uid,
				token_expired: res.tokenExpired,
				push_clientid: cid,
				unipush_clientid: cid,
	
				login_cnt: 1,
				create_date: nowdate,
				last_active_date: nowdate,
				last_active_ip: this.ctx.data.ip || this.ctx.context.CLIENTIP
			});
		}
		
		// 日志记录
		this.uidlog(res)
		return res
	}
	
	// 日志记录
	async uidlog(res, type = 'login') {
		let data = {
			deviceId: this.ctx.data.deviceId || this.ctx.context.DEVICEID,
			ip: this.ctx.data.ip || this.ctx.context.CLIENTIP,
			type,
			ua: this.ctx.context.CLIENTUA,
			create_date: Date.now()
		};
	
		Object.assign(data, res.code === 0 ? {
			user_id: res.uid,
			state: 1
		} : {
			state: 0
		});
	
		return this.db.collection('uni-id-log').add(data);
	}
}